#include "searchwidget.h"
#include "ui_searchwidget.h"
#include"httpmgr.h"
#include"QMessageBox"
#include<QThread>
SearchWidget::SearchWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::SearchWidget)
{
    ui->setupUi(this);

    ui->musicName->setMaximumWidth(300);
    ui->tipString->setAlignment(Qt::AlignBottom);
    ui->tipString->setText("的相关搜索如下");
    ui->tabWidget->setCurrentIndex(0);

    this->setStyleSheet(R"(
        QWidget#widget{
            background-color: qconicalgradient(cx:0.665746, cy:0.216, angle:0, stop:0
                rgba(86, 132, 183, 75), stop:1 rgba(166, 193, 255, 35));
        }
        QLabel#musicName{
            font:34px "宋体" black;
            font-weight:bold;
        }
        QLabel#tipString{
            font:20px "宋体" black;
            color:rgba(0,0,0,100);
        }
        QTabWidget{
            font:20px "宋体" black;
        }
        QTabBar::tab{
            background-color:rgba(0,0,0,0);
        }
        QTabBar::tab:hover{
            color:rgba(100,54,200,225);
        }
        QTabBar::tab:selected{
            font:26px;
            color:rgba(131,55,197,200);
        }
        QTabWidget::pane{
            background-color:rgba(0,0,0,0);
            border: 1px solid white;
        }
        QListWidget{
            border:none;
            font:18px "宋体";
            background-color:rgba(0,0,0,0);
        }
        QListWidget::item{
            height:60px;
            border-radius:10px;
            padding-left:20px;
            padding-right:20px;
            margin-top:2px;
            margin-bottom:2px;

            margin-left:10px;
            margin-right:10px;
        }
        QListWidget::item:hover{
            background-color: rgba(255,255,255,100);
        }
        QListWidget::item:selected{
            background-color: rgba(131,255,197,100);
        }
    )");
    /*
        对于QTabWidget的样式表设置好像格外的复杂，不知道为什么background-color一直设置不上
    */

    ui->listWidget->setFocusPolicy(Qt::NoFocus);
    ui->listWidget->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->listWidget->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    connect(HttpMgr::GetInstance().get(),&HttpMgr::sig_search_mod_finish,this,&SearchWidget::slot_search_mod_finish);
}

SearchWidget::~SearchWidget()
{
    delete ui;
}



void SearchWidget::updataListWidget()
{
    deleteItem();

    for(int q=0;q<songList.size();q++){
        QListWidgetItem* item=new QListWidgetItem(ui->listWidget);
        ui->listWidget->addItem(item);

        songItem* itemWidget=new songItem(ui->listWidget);
        ui->listWidget->setItemWidget(item,itemWidget);

        itemWidget->getLablel()->setText(QString::number(q+1)+".");
        itemWidget->getSongLabel()->setText(songList[q].musicName);
        itemWidget->getNameLabel()->setText(songList[q].artistsName);
        int minutes=songList[q].musicDuration/60000,seconds=(songList[q].musicDuration%60000)/1000;
        QString tim=QString::asprintf("%02d:%02d",minutes,seconds);
        itemWidget->getDurationLabel()->setText(tim);

        if(!songList[q].fee){
            itemWidget->getvip()->hide();
        }

    }
}

void SearchWidget::deleteItem()
{
    for(int q=ui->listWidget->count()-1;q>=0;q--){
        QListWidgetItem* item = ui->listWidget->takeItem(q); // 从列表中移除项但不删除
        if (item) {
            QWidget* widget = ui->listWidget->itemWidget(item); // 获取关联的 QWidget
            delete widget; // 删除 QWidget
            delete item; // 删除 QListWidgetItem
        }
    }
}

QLabel *SearchWidget::getSongLab()
{
    return ui->musicName;
}

QList<songInfo> SearchWidget::getSongList()
{
    return songList;
}

void SearchWidget::on_listWidget_itemDoubleClicked(QListWidgetItem *item)
{
    emit listDoublePress(ui->listWidget->row(item));

}

void SearchWidget::slot_search_mod_finish(ReqId id, QString res, ErrorCodes err)
{
    if(err!=ErrorCodes::SUCCESS){
        qDebug()<<"请求搜索音乐网络错误";
        return;
    }
    QJsonParseError err2;
    QJsonDocument json_recv=QJsonDocument::fromJson(res.toUtf8(),&err2);
    if(err2.error != QJsonParseError::NoError){        //数据获取失败（一般是网络未连接等...）
        QString title="API数据获取";
        QString text="JSON歌曲数据获取失败...";
        QMessageBox::critical(this,title,text);
        return ;
    }

    //解析数据并保存进QList
    if(!songList.empty()) {
        songList.clear();
    }
    qDebug()<<"获取歌曲成功";
    QJsonObject root=json_recv.object();
    QStringList keys=root.keys();
    if(keys.contains("result")){
        QJsonObject obj1=root["result"].toObject();
        QStringList strl=obj1.keys();
        if(strl.contains("songs")){  //songs 内就是歌曲信息 数组
            QJsonArray songArr=obj1["songs"].toArray();          //songArr歌曲数组
            //qDebug()<<songArr.size();
            songList.resize(songArr.size());
            // int num=0;//计算免费歌曲数量
            for(int i=0;i<songArr.size();i++){
                // int flag=object["fee"].toInt();
                // //判断是否免费
                // if(!flag){//免费
                //     num++;

                // }

                QJsonObject object = songArr[i].toObject();
                songList[i].musicId = QString::number(object["id"].toVariant().toLongLong());// 音乐id
                songList[i].musicDuration = object["duration"].toInt(); // 音乐长度
                songList[i].musicName = object["name"].toString();      // 音乐名
                songList[i].fee=object["fee"].toInt();
                QStringList artistsKeys = object.keys();
                if(artistsKeys.contains("artists"))
                {
                    QJsonArray artistsArray = object["artists"].toArray();       //歌手名
                    if(!artistsArray.empty()){
                        songList[i].artistsName=artistsArray[0].toObject()["name"].toString();
                    }
                }

            }
            // songList.resize(num);
        }
    }

    updataListWidget();

}


